import {
  Component, OnInit, ViewChild, Input, Output, EventEmitter} from '@angular/core';
import {ModalDirective} from "ngx-bootstrap";
import {APARTMENT} from "../../service/apartment.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {CONTRACT} from "../../service/contract.service";
import {WfToast} from "../../utils/toast.utils";
import {ConfirmCheckoutModalViewComponent} from "../confirm-checkout-modal-view/confirm-checkout-modal-view.component";
import {LocalStorage} from "../../app.local-storage";

@Component({
  selector: 'app-exchange-modal-view',
  templateUrl: './exchange-modal-view.component.html',
  styleUrls: ['./exchange-modal-view.component.scss']
})
export class ExchangeModalViewComponent implements OnInit {


  @ViewChild(ConfirmCheckoutModalViewComponent) public confirmCheckoutModal:any;
  @Input('showModal') public isModalShown: boolean = false;
  @Output('modalClose') public modalClose = new EventEmitter();
  @Input()
  contractId:number;
  @Input()
  apartmentName:string;
  public apartmentList:any=[];
  public exchangeForm:FormGroup;
  public disabled:boolean = true;
  public currentApartmentId:number;
  constructor(private apartmentApi:APARTMENT,
              private formBuilder:FormBuilder,
              private contract:CONTRACT,
              private toast: WfToast,
              private localStorage:LocalStorage) {
    this.exchangeForm = this.formBuilder.group({
      apartment:[''],
      houseNo:['']
    });
  }

  loadApartment(){
    this.apartmentApi.getList({},(res:any)=>{
      console.log(res);
      let list:any=[];
      for(let item of res.content){
        let data:any={
          id:item.id,
          name:item.name
        }
        list.push(data);
      }
      this.apartmentList = list;
      for(let item of this.apartmentList){
        if(item.name==this.apartmentName){
          return this.currentApartmentId = item.id;
        }
      }
    })
  }

  doExchangeRoom(){
    let reqData:any={
      id:this.contractId,
      newApartmentId:this.exchangeForm.get('apartment').value,
      newHouseNo:this.exchangeForm.get('houseNo').value,
      // 1-退租，2-续约，3-换房，4-转租
      operation:3
    }
    let close:any = this.modalClose;
    this.contract.Checkout(reqData,(res:any)=>{
      this.confirmCheckoutModal.isModalShown = true;
      close.emit(false);
    })
  }

  ngOnInit() {


  }

  public showModal(): void {
    this.isModalShown = true;
    this.loadApartment();
  }

  public onHidden(): void {
    this.isModalShown = false;
  }

  closeConfirmCheckoutModal(result:any){
    this.confirmCheckoutModal.onHidden();
  }
}
